import { defineStore } from "pinia";
import { ref, computed } from "vue";

// 初始状态
function initState() {
    return {
        // 用户信息
        user: {
            id: null,
            username: "",
            phone: "",
            email: "",
            realName: "",
            avatar: "",
        },
        // 认证令牌
        token: "",
        // 是否已登录
        isLoggedIn: false,
    };
}

export const useUserStore = defineStore("userStore", () => {
    // 状态
    const state = ref(initState());

    // 计算属性
    const userId = computed(() => state.value.user.id);
    const username = computed(() => state.value.user.username);
    const isLoggedIn = computed(() => state.value.isLoggedIn);

    // 设置用户登录状态
    function setLoginState(userData) {
        state.value.user = {
            ...state.value.user,
            ...userData
        };
        state.value.token = userData.token || "";
        state.value.isLoggedIn = true;
    }

    // 退出登录
    function logout() {
        // 重置状态
        Object.assign(state.value, initState());
    }

    return {
        state,
        userId,
        username,
        isLoggedIn,
        setLoginState,
        logout
    };
}, {
    persist: {
        key: 'user-store', // 存储的key名
        storage: localStorage, // 存储方式，默认为localStorage,sessionStorage会话级存储，关闭标签页后失效
       // 选择性持久化某些字段（默认持久化所有 state）
        paths: ['state.token', 'state.user', 'state.isLoggedIn'] // 只持久化token和user信息
    }
});
